﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MyTime.ProviderFactory.Entities;
namespace MyTime.CsvProvider
{
    public class Service : MyTime.ProviderFactory.MyTimeProviderBase
    {
        private string _csvFilePath = string.Empty;
        private const char _delimiter = '|';
        private CsvHelper _csvHelper;
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            _csvFilePath = config["filePath"];
            if (string.IsNullOrWhiteSpace(_csvFilePath))
            {
                string fileName = "My.Time";
                string folder = Environment.CurrentDirectory;//Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                _csvFilePath = Path.Combine(folder, fileName);
                config["filePath"] = _csvFilePath;
            }
            if (!File.Exists(_csvFilePath))
                File.WriteAllText(_csvFilePath, string.Format("TASK{0}STARTTIME{0}ENDTIME", _delimiter, Environment.NewLine), Encoding.UTF8);

            _csvHelper = new CsvHelper(_csvFilePath, _delimiter, 1);
        }

        public override string Name
        {
            get
            {
                return "CsvProvider";
            }
        }

        public override void AddTask(ITimeItem newTimeItem)
        {
            //get our current timeitem
            ITimeItem current = GetCurrentTimeItem();
            if (current != null)
            {
                if (current.Task == newTimeItem.Task && current.StartTime.Date == newTimeItem.StartTime.Date)
                {
                    if (newTimeItem.EndTime != null && newTimeItem.EndTime > DateTime.MinValue)
                    {
                        _csvHelper.UpdateRow(new string[] { current.Task, current.StartTime.ToString(), newTimeItem.EndTime.ToString() }, 0, 1);
                    }
                    return;

                }
                else
                {
                    //update current item because it's not our current anymore
                    _csvHelper.UpdateRow(new string[] { current.Task, current.StartTime.ToString(), DateTime.Now.ToString() }, 0, 1);
                }
            }
            //if non was found then we add a new row to the csv
            _csvHelper.AddRow(new string[] { newTimeItem.Task, newTimeItem.StartTime.ToString(), string.Empty });
        }
        public override IEnumerable<ProviderFactory.Entities.ITimeItem> GetAllTime()
        {
            int rowNr = 0;
            var timeItems = from row in _csvHelper.GetCsvData()
                            select Entities.CsvTimeItem.Parse(row, rowNr++);
            return timeItems;
        }
        public override IEnumerable<ProviderFactory.Entities.ITimeItem> GetTodaysTimeItems()
        {
            int rowNr = 0;
            var timeItems = from row in _csvHelper.GetCsvData()
                            where DateTime.Parse(row[1]).Date == DateTime.Now.Date
                            select Entities.CsvTimeItem.Parse(row, rowNr++);
            return timeItems;
        }

        public override ProviderFactory.Entities.ITimeItem GetCurrentTimeItem()
        {
            return GetTodaysTimeItems().Where(i => i.Current).FirstOrDefault();
        }

        public override bool ImportOldData(double version, params string[] param)
        {
            try
            {
                string filePath = param[0];
                //TODO: something with version...
                string[] csvRows = System.IO.File.ReadAllLines(filePath, Encoding.UTF8);
                var timeItems = new List<Entities.CsvTimeItem>();
                var filteredTimeItems = new List<Entities.CsvTimeItem>();
                int rowNr = 0;
                foreach (string row in csvRows)
                {
                    string[] cols = row.Split(';');
                    var item = new Entities.CsvTimeItem(cols[1], DateTime.Parse(cols[0]), rowNr, false);
                    timeItems.Add(item);
                    rowNr++;
                }
                //timeItems = timeItems.OrderBy(i => i.StartTime).ToList();
                var days = timeItems.GroupBy(item => item.StartTime.Date).ToList();
                rowNr = 0;
                foreach (var dayItems in days)
                {
                    var tasks = dayItems.Select(i => i.Task).Distinct();
                    foreach (var task in tasks)
                    {
                        var startDate = dayItems.Where(i => i.Task == task).Min(i => i.StartTime);
                        var endDate = dayItems.Where(i => i.Task == task).Max(i => i.StartTime);
                        if (startDate == endDate)
                            endDate = endDate.AddHours(1);
                        filteredTimeItems.Add(new Entities.CsvTimeItem(task, startDate, endDate, rowNr));
                        rowNr++;
                    }
                }
                var oldCsvData = filteredTimeItems.OrderBy(i => i.StartTime).Select(i => new string[] { i.Task, i.StartTime.ToString(), i.EndTime.ToString() });
                var currentData = _csvHelper.CsvData.ToList();
                System.IO.File.WriteAllText(_csvHelper.FilePath, string.Empty);
                foreach (var row in oldCsvData)
                {
                    _csvHelper.AddRow(row);
                }
                foreach (var row in currentData)
                {
                    _csvHelper.AddRow(row);
                }
            }
            catch (FileNotFoundException fex)
            {
                throw fex;
            }
            catch (FileLoadException flex)
            {
                throw flex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }
    }
}
